package com.helloworld.chat.dao.impl;

import com.helloworld.chat.dao.FriendRequestDao;
import com.helloworld.chat.entity.FriendRequest;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by xdzy on 2017/6/29.
 */
@Repository
public class FriendRequestDaoImpl implements FriendRequestDao {
    private SessionFactory sessionFactory;
    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void addFriendRequest(FriendRequest friendRequest) {
        sessionFactory.getCurrentSession().save(friendRequest);
    }

    @Override
    public FriendRequest getFriendRequest(int id) {
        return sessionFactory.getCurrentSession().get(FriendRequest.class,id);
    }

    @Override
    public FriendRequest getFriendRequest(int senderId, int receiveId) {
        return sessionFactory.getCurrentSession()
                .createQuery("from FriendRequest  where senderId=:sid and receiverId=:rid",FriendRequest.class)
                .setParameter("sid",senderId).setParameter("rid",receiveId).uniqueResult();
    }

    @Override
    public List<FriendRequest> getFriendRequestList(int uid) {

        return null;
    }

    @Override
    public List<FriendRequest> getMyFriendRequestList(int uid) {
        return sessionFactory.getCurrentSession()
                .createQuery("from FriendRequest where senderId=:sid ",FriendRequest.class)
                .setParameter("sid",uid).list();
    }

    @Override
    public List<FriendRequest> getReceiveFriendRequestList(int uid) {
        return sessionFactory.getCurrentSession()
                .createQuery("from FriendRequest  where receiverId=:rid",FriendRequest.class)
                .setParameter("rid",uid).list();
    }

    @Override
    public int getRequestCount(int uid) {
        return sessionFactory.getCurrentSession()
                .createQuery("select count(*) from FriendRequest  where receiverId=:rid",Long.class)
                .setParameter("rid",uid).uniqueResult().intValue();
    }

    @Override
    public void deleteRequest(int id) {
       FriendRequest friendRequest=sessionFactory.getCurrentSession().get(FriendRequest.class,id);
        sessionFactory.getCurrentSession().delete(friendRequest);
    }


}
